package com.cristina.attention.service;

import com.cristina.attention.config.bean.SecurityProperties;
import com.cristina.attention.service.dto.JwtUserDto;
import com.cristina.attention.service.dto.OnlineUserDto;
import com.cristina.attention.utils.EncryptUtils;
import com.cristina.attention.utils.RedisUtils;
import com.cristina.attention.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author superman
 * @Date 2021/11/17 23:20
 **/
@Service
@Slf4j
public class OnlineUserService {

    private final RedisUtils redisUtils;
    private final SecurityProperties properties;

    public OnlineUserService(RedisUtils redisUtils, SecurityProperties properties) {
        this.redisUtils = redisUtils;
        this.properties = properties;
    }

    /**
     * 保存在线用户信息
     * @param jwtUserDto /
     * @param token /
     * @param request /
     */
    public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request){
        String ip = StringUtils.getIp(request);
        String browser = StringUtils.getBrowser(request);
        String address = StringUtils.getCityInfo(ip);
        OnlineUserDto onlineUserDto = null;
        try {
            onlineUserDto = new OnlineUserDto(jwtUserDto.getUsername(), browser , ip, address, EncryptUtils.desEncrypt(token), new Date());
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000);
    }

    /**
     * 查询用户
     * @param key /
     * @return /
     */
    public OnlineUserDto getOne(String key) {
        return (OnlineUserDto)redisUtils.get(key);
    }

    /**
     * 退出登录
     * @param token /
     */
    public void logout(String token) {
        String key = properties.getOnlineKey() + token;
        redisUtils.del(key);
    }

}
